package com.joolun.cloud.common.security.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.joolun.cloud.common.core.constant.SecurityConstants;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * @author
 * 认证授权相关工具类
 */
@Slf4j
@UtilityClass
public class ThridPartyHttpsUtils {

	String WX_AUTHORIZATION_CODE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token" +
			"?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

	String QQ_AUTHORIZATION_CODE_URL = "https://graph.qq.com/oauth2.0/token" +
			"?client_id=%s&client_secret=%s&code=%s&grant_type=authorization_code&redirect_uri=%s";

	String QQ_AUTHORIZATION_ME_URL = "https://graph.qq.com/oauth2.0/me" +
			"?access_token=%s";

	/**
	 * 微信获取OPENID
	 */
	public String getWxOpenId(String appId,String appSecret,String code){
		String url = String.format(WX_AUTHORIZATION_CODE_URL
				, appId, appSecret, code);
		String result = HttpUtil.get(url);
		log.debug("微信响应报文:{}", result);
		JSONObject jSONObject  = JSONUtil.parseObj(result);
		if(jSONObject.get("errcode") != null){
			throw new RuntimeException(jSONObject.getStr("errmsg"));
		}
		String openId = jSONObject.get("openid").toString();
		return openId;
	}

	/**
	 * QQ获取OPENID
	 * https://wiki.connect.qq.com/%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7openid_oauth2-0
	 * @param appId
	 * @param appSecret
	 * @param code
	 * @param redirectUri
	 * @return
	 */
	public String getQqOpenId(Integer appId,String appSecret,String code,String redirectUri){
		String url = String.format(QQ_AUTHORIZATION_CODE_URL
				, appId, appSecret, code, redirectUri);
		String result = HttpUtil.get(url);
		log.debug("QQ响应报文:{}", result);
//		access_token=09A336EFD0100DC8C102E1870396319E&expires_in=7776000&refresh_token=7D8A6E9C88C9AA8189368E6A0F2B730F
		String accessToken = result.split("&")[0].split("=")[1];

		url = String.format(QQ_AUTHORIZATION_ME_URL, accessToken);
		result = HttpUtil.get(url);
//		callback( {"client_id":"101888362","openid":"714DE5D387C23304B13C023D33BC7621"} );
		result = result.replace("callback( ", "");
		result = result.replace("); ", "");
		JSONObject jSONObject  = JSONUtil.parseObj(result);
		String openId = jSONObject.get("openid").toString();
		return openId;
	}
}
